package com.aidex.system.service.impl;

import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.core.domain.entity.SysRole;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.service.impl.BasicServiceImpl;
import com.aidex.common.exception.BizException;
import com.aidex.common.exception.CustomException;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.spring.SpringUtils;
import com.aidex.system.common.SysErrorCode;
import com.aidex.system.domain.SysRoleDept;
import com.aidex.system.domain.SysRoleMenu;
import com.aidex.system.domain.SysUserRole;
import com.aidex.system.mapper.SysRoleDeptMapper;
import com.aidex.system.mapper.SysRoleMapper;
import com.aidex.system.mapper.SysRoleMenuMapper;
import com.aidex.system.mapper.SysUserRoleMapper;
import com.aidex.system.service.SysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

@Service
public class SysRoleServiceImpl extends BasicServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired(required = false)
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired(required = false)
    private SysUserRoleMapper userRoleMapper;

    @Autowired(required = false)
    private SysRoleDeptMapper roleDeptMapper;


    @Override
    public Set<String> selectRolePermissionByUserId(String userId) {
        List<SysRole> perms = mapper.selectListByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysRole> selectListByUser(QueryWrapper<SysRole> wrapper) {
        return mapper.selectListByUser(wrapper);
    }

    @Override
    public void checkRoleNameUnique(SysRole role) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name", role.getRoleName());
        wrapper.ne("id", role.getId());
        if (mapper.selectCount(wrapper) > 0) {
            throw new BizException(SysErrorCode.B_SYSROLE_RoleNameAlreadyExist);
        }
    }

    @Override
    public void checkRoleKeyUnique(SysRole role) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("role_key", role.getRoleKey());
        wrapper.ne("id", role.getId());
        if (mapper.selectCount(wrapper) > 0) {
            throw new BizException(SysErrorCode.B_SYSROLE_RoleKeyAlreadyExist);
        }
    }

    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotBlank(role.getId()) && role.isAdmin()) {
            throw new CustomException("不允许操作超级管理员角色");
        }
    }

    @Override
    public int countUserRoleByRoleId(String roleId) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        return userRoleMapper.selectCount(wrapper);
    }

    @Override
    @Transactional
    public int insert(SysRole role) {
        checkRoleNameUnique(role);
        checkRoleKeyUnique(role);
        // 新增角色信息
        super.insert(role);
        return insertRoleMenu(role);
    }

    @Override
    @Transactional
    public int updateById(SysRole role) {
        checkRoleNameUnique(role);
        checkRoleKeyUnique(role);
        super.updateById(role);
        UpdateWrapper<SysRoleMenu> wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id", role.getId());
        roleMenuMapper.delete(wrapper);
        return insertRoleMenu(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role) {
        // 修改角色信息
        super.updateById(role);
        // 删除角色与部门关联
        UpdateWrapper<SysRoleDept> wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id", role.getId());
        roleDeptMapper.delete(wrapper);
        if ("2".equals(role.getDataScope())) {
            // 新增角色和部门信息（数据权限）
            return insertRoleDept(role);
        } else {
            return 1;
        }
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (String menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            for (SysRoleMenu roleMenu : list) {
                rows += roleMenuMapper.insert(roleMenu);
            }
        }
        return rows;
    }

    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (String deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            for (SysRoleDept roleDept : list) {
                rows += roleDeptMapper.insert(roleDept);
            }
        }
        return rows;
    }

    @Override
    @Transactional
    public int deleteById(Serializable roleId) {
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id", roleId);
        // 删除角色与菜单关联
        roleMenuMapper.delete(wrapper);
        // 删除角色与部门关联
        roleDeptMapper.delete(wrapper);
        // 删除角色与用户关联
        userRoleMapper.delete(wrapper);
        return mapper.deleteById(roleId);
    }

    @Override
    @Transactional
    public int deleteBatchIds(Collection<? extends Serializable> roleIds) {
        int flag = 0;
        for (Serializable roleId : roleIds) {
            flag += deleteById(roleId);
        }
        return flag;
    }

    @Override
    public int findMaxSort() {
        return NumberUtils.nextOrder(mapper.findMaxSort());
    }

    @Override
    @Transactional
    public int batchInsert(List<SysRole> roleList) {
        if (!CollectionUtils.isEmpty(roleList)) {
            for (SysRole role : roleList) {
                if (StringUtils.isNotBlank(role.getHandleType()) && "add".equals(role.getHandleType())) {
                    //获取最大编号
                    role.setSort(findMaxSort() + "");
                    role.setId("");//清空前台临时ID
                    role.setDataScope("2");
                    super.insert(role);
                } else if (StringUtils.isNotBlank(role.getHandleType()) && "edit".equals(role.getHandleType())) {
                    super.updateById(role);
                } else if (StringUtils.isNotBlank(role.getHandleType()) && "delete".equals(role.getHandleType())) {
                    //删除角色的同时需要删除对应的角色下用户
                    deleteById(role.getId());
                }
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int deleteRoleUser(String roleId, String[] userIds) {
        UpdateWrapper<SysUserRole> wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id", roleId);
        wrapper.in("user_id", userIds);
        return userRoleMapper.delete(wrapper);
    }

    @Override
    @Transactional
    public int saveRolePortlet(SysRole role) {
        if ("add".equals(role.getOption())) {
            return insertRoleMenu(role);
        } else {
            return deleteRoleMenu(role.getId(), role.getMenuIds());
        }
    }

    public int deleteRoleMenu(String roleId, String[] menuIds) {
        UpdateWrapper<SysRoleMenu> wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id", roleId);
        wrapper.in("menu_id", menuIds);
        return roleMenuMapper.delete(wrapper);
    }

    @Override
    public void checkRoleDataScope(String roleId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            wrapper.eq("id", roleId);
            List<SysRole> roles = SpringUtils.getAopProxy(this).selectList(wrapper);
            if (StringUtils.isEmpty(roles)) {
                throw new BizException("没有权限访问角色数据！");
            }
        }
    }
}
